package com.yyi.springcloud.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.yyi.springcloud.common.SearchResult;
import com.yyi.springcloud.dao.SearchInfoMapper;
import com.yyi.springcloud.dao.TestProdInfoValueMapper;
import com.yyi.springcloud.entities.*;
import com.yyi.springcloud.service.Local_SearchInfoService;
import com.yyi.springcloud.service.Local_TestUnitConfigService;
import com.yyi.springcloud.utils.StringUtil;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class Local_SearchInfoServiceImpl implements Local_SearchInfoService {
	@Resource
	private SearchInfoMapper searchInfoDao;

	@Autowired
	private SolrServer solrServer;

	@Resource
	private TestProdInfoValueMapper testProdInfoValueMapper;

	@Autowired
	private Local_TestUnitConfigService testUnitConfigService;

	public SearchInfoMapper getSearchInfoDao() {
		return searchInfoDao;
	}

	public void setSearchInfoDao(SearchInfoMapper searchInfoDao) {
		this.searchInfoDao = searchInfoDao;
	}

	public TestProdInfoValueMapper getTestProdInfoValueMapper() {
		return testProdInfoValueMapper;
	}

	public void setTestProdInfoValueMapper(TestProdInfoValueMapper testProdInfoValueMapper) {
		this.testProdInfoValueMapper = testProdInfoValueMapper;
	}

	@Override
	public List<SearchInfoModel> getSearchInfo(String keyword) {

		List<SearchInfoModel> SearchInfoModel = new ArrayList<SearchInfoModel>();
		// 分页处理
		PageHelper.startPage(1, 10);
		// Example example = new Example(Weigh_F_Isp.class);
		// example.createCriteria().andLessThan("id", 50);
		SearchInfoModel = searchInfoDao.selectSearchInfo(keyword);
		// 取记录总条数
		PageInfo<SearchInfoModel> pageInfo = new PageInfo<SearchInfoModel>(SearchInfoModel);

		return pageInfo.getList();
	}

	@Override
	public SearchResult searchService(String queryString, int page, int rows) throws Exception {
		// 创建查询对象
		SolrQuery query = new SolrQuery();
		// 设置查询条件
		query.setQuery(queryString);
		// 设置分页
		query.setStart((page - 1) * rows);
		query.setRows(rows);
		// 设置默认搜素域
		query.set("df", "testProdInfoValue");
		// 设置高亮显示
		query.setHighlight(true);
		query.addHighlightField("itemcontent1");
		query.addHighlightField("itemcontent4");
		query.setHighlightSimplePre("<em style=\"color:red\">");
		query.setHighlightSimplePost("</em>");
		// 执行查询
		SearchResult searchResult = searchDao(query);
		// 计算查询结果总页数
		long recordCount = searchResult.getRecordCount();
		long pageCount = recordCount / rows;
		if (recordCount % rows > 0) {
			pageCount++;
		}
		searchResult.setPageCount(pageCount);
		searchResult.setCurPage(page);

		return searchResult;
	}

	public SearchResult searchDao(SolrQuery query) throws Exception {
		// 返回值对象
		SearchResult result = new SearchResult();
		// 根据查询条件查询索引库
		QueryResponse queryResponse = solrServer.query(query);
		// 取查询结果
		SolrDocumentList solrDocumentList = queryResponse.getResults();
		// 取查询结果总数量
		result.setRecordCount(solrDocumentList.getNumFound());
		// 数据列表
		List<Object> itemList = new ArrayList<>();
		// 取高亮显示
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		for (SolrDocument solrDocument : solrDocumentList) {
			TestProdInfoValueModel model = new TestProdInfoValueModel();
			model.setPrimarykey((String) solrDocument.get("id"));
			// 获取高亮显示的结果
			List<String> list = highlighting.get(solrDocument.get("id")).get("itemcontent1");
			String itemcontent1 = "";
			if (list != null && list.size() > 0) {// 有高亮显示
				itemcontent1 = list.get(0);
			} else {// 没有高亮显示
				itemcontent1 = (String) solrDocument.get("itemcontent1");
			}

			List<String> list4 = highlighting.get(solrDocument.get("id")).get("itemcontent4");
			String itemcontent4 = "";
			if (list4 != null && list4.size() > 0) {// 有高亮显示
				itemcontent4 = list4.get(0);
			} else {// 没有高亮显示
				itemcontent4 = (String) solrDocument.get("itemcontent4");
			}

			model.setItemcontent1(itemcontent1);
			model.setItemcontent4(itemcontent4);
			model.setLabcode((String) solrDocument.get("labcode"));
			model.setItemcontent2((String) solrDocument.get("itemcontent2"));
			model.setItemcontent3((String) solrDocument.get("itemcontent3"));
			model.setItemcontent5((String) solrDocument.get("itemcontent5"));
			model.setItemcontent6((String) solrDocument.get("itemcontent6"));
			model.setItemcontent7((String) solrDocument.get("itemcontent7"));
			model.setItemcontent8((String) solrDocument.get("itemcontent8"));
			model.setItemcontent9((String) solrDocument.get("itemcontent9"));
			model.setItemcontent10((String) solrDocument.get("itemcontent10"));
			itemList.add(model);
		}
		result.setList(itemList);
		return result;
	}

	// 3.导入数据到索引库----solr专用
	@Override
	public String importAllSearchData() {
		try {
			// 查询所有的铭牌信息记录
			Example example = new Example(TestProdInfoValueModel.class);
			Example.Criteria criteria = example.createCriteria();
			List<TestProdInfoValueModel> allSearchData = testProdInfoValueMapper.selectByExample(example);
			// 把商品信息写入索引库
			for (TestProdInfoValueModel model : allSearchData) {
				// 创建一个SolrInputDocument对象
				SolrInputDocument document = new SolrInputDocument();
				document.setField("id", model.getPrimarykey());

				// collection1\conf\schema.xml中业务字段的配置
				document.setField("labcode", model.getLabcode());
				document.setField("itemcontent1", model.getItemcontent1());
				document.setField("itemcontent2", model.getItemcontent2());
				document.setField("itemcontent3", model.getItemcontent3());
				document.setField("itemcontent4", model.getItemcontent4());
				document.setField("itemcontent5", model.getItemcontent5());
				document.setField("itemcontent6", model.getItemcontent6());
				document.setField("itemcontent7", model.getItemcontent7());
				document.setField("itemcontent8", model.getItemcontent8());
				document.setField("itemcontent9", model.getItemcontent9());
				document.setField("itemcontent10", model.getItemcontent10());

				// 添加其余字段 用于历史数据查询:gy2018年8月14日
				document.setField("begindatetime", StringUtil.formatDate(model.getBegindatetime()));
				document.setField("enddatetime", StringUtil.formatDate(model.getEnddatetime()));
				document.setField("testnow", model.getTestnow());
				document.setField("testunitno", model.getTestunitno());

				// 写入索引库
				solrServer.add(document);
			}
			// 提交修改
			solrServer.commit();
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
		return "success";
	}

	@Override
	public DataTablesPage<TestProdInfoValueVo> historyDataSearch(int draw, String queryString, int start, int rows,
                                                                 String startDate, String endDate) throws Exception {
		// 创建查询对象
		SolrQuery query = new SolrQuery();
		// 设置查询条件
		if (queryString != null && queryString != "") {
			query.setQuery(queryString);
		}
		// 设置开测时间的查询范围
		if (startDate != null && endDate != null) {
			query.setQuery("begindatetime:[" + str2SolrDate(startDate) + " TO " + str2SolrDate(endDate) + "]");
		}
		// 设置分页
		query.setStart(start);
		query.setRows(rows);
		// 设置默认搜素域
		query.set("df", "testProdInfoValue");

		// 根据查询条件查询索引库
		QueryResponse queryResponse = solrServer.query(query);
		// 取查询结果
		SolrDocumentList solrDocumentList = queryResponse.getResults();

		// 遍历数据结果，封装需要的返回值
		List<TestProdInfoValueVo> results = new ArrayList<>();
		for (SolrDocument solrDocument : solrDocumentList) {
			String itemcontent1 = (String) solrDocument.getFieldValue("itemcontent1");
			String itemcontent2 = (String) solrDocument.getFieldValue("itemcontent2");
			String itemcontent3 = (String) solrDocument.getFieldValue("itemcontent3");
			String itemcontent4 = (String) solrDocument.getFieldValue("itemcontent4");
			String itemcontent5 = (String) solrDocument.getFieldValue("itemcontent5");
			String itemcontent6 = (String) solrDocument.getFieldValue("itemcontent6");
			String itemcontent7 = (String) solrDocument.getFieldValue("itemcontent7");
			String itemcontent8 = (String) solrDocument.getFieldValue("itemcontent8");
			String itemcontent9 = (String) solrDocument.getFieldValue("itemcontent9");
			String itemcontent10 = (String) solrDocument.getFieldValue("itemcontent10");
			String itemcontent11 = (String) solrDocument.getFieldValue("itemcontent11");
			String begindatetime = StringUtil.utc2BeiJingDate((String) solrDocument.getFieldValue("begindatetime"));
			String enddatetime = StringUtil.utc2BeiJingDate((String) solrDocument.getFieldValue("enddatetime"));
			String testnow = (String) solrDocument.getFieldValue("testnow");
			String testunitno = (String) solrDocument.getFieldValue("testunitno");
			String labcode = (String) solrDocument.getFieldValue("labcode");

			// 根据台位编号查询台位名称
			TestUnitConfigModel testUnitConfigModel = new TestUnitConfigModel();
			testUnitConfigModel.setTestunitno(Integer.parseInt(testunitno));
			String testUnitName = "";
			List<TestUnitConfigModel> testUnitConfigModels = testUnitConfigService
					.getTestUnitByCondition(testUnitConfigModel);
			if (testUnitConfigModels.size() > 0) {
				testUnitName = testUnitConfigModels.get(0).getTestunitname();
			}

			// 设置是否开测
			String isTest = "否";
			if (testnow == "1") {
				isTest = "是";
			}

			TestProdInfoValueVo testProdInfoValueVo = new TestProdInfoValueVo(testUnitName, begindatetime, enddatetime,
					isTest, itemcontent1, itemcontent2, itemcontent3, itemcontent4, itemcontent5, itemcontent6,
					itemcontent7, itemcontent8, itemcontent9, itemcontent10, itemcontent11);
			results.add(testProdInfoValueVo);
		}

		// 封装分页 返回
		return new DataTablesPage<TestProdInfoValueVo>(draw, solrDocumentList.getNumFound(),
				solrDocumentList.getNumFound(), results, rows);
	}

	/**
	 * 时间字符串转solr时间格式
	 * 
	 * @Description:
	 * @author 高杨
	 * @date 2018年8月17日 下午5:01:23
	 * @return String
	 */
	private String str2SolrDate(String strDate) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(strDate, pos);
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
		sdf2.setTimeZone(TimeZone.getTimeZone("UTC"));
		String result = sdf1.format(strtodate) + "T" + sdf2.format(strtodate) + "Z";
		return result;
	}
}
